/**
 * 
 */
package ua.ws.feedsreader.gen;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
 * @author ricardo
 *
 */
public class HTMLGenerator {
	
	private String contextPath;
	private String tempPath = "/temps/";
	private String xsltPath = "/ua/ws/feedsreader/xslts/";
	
	public HTMLGenerator(String realPath) {
		contextPath = realPath;
	}

	private Transformer getTransformer(String xslt) throws TransformerConfigurationException {
		TransformerFactory tFactory = TransformerFactory.newInstance();
		return tFactory.newTransformer(new StreamSource( contextPath+xsltPath + xslt ));
		
	}
	
	public String generateHTMLSearchResult(String result) throws IOException, TransformerException {
		File tempdir = getTempDir();
		File createTempFile = File.createTempFile("search", ".xml", tempdir );
		FileWriter fileWriter = new FileWriter(createTempFile);
		BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
		bufferedWriter.write("<search>" + result + "</search>" );
		bufferedWriter.flush();
		bufferedWriter.close();
		fileWriter.close();
		StringWriter w = new StringWriter();
		getTransformer("search.xsl").transform( new StreamSource( createTempFile ), new StreamResult( w ) );
		w.flush();
		createTempFile.delete();
		String resultTransformed = w.toString();
		w.close();
		return resultTransformed;
		
	}
	
	private File getTempDir() {
		File file = new File(contextPath+tempPath);
		if( !file.exists() ) {
			file.mkdirs();
		}
		return file;
	}
	
	public String generateHTMLTop10(String result) throws IOException, TransformerConfigurationException, TransformerException {
		File tempdir = getTempDir();
		File createTempFile = File.createTempFile("top10", ".xml", tempdir );
		FileWriter fileWriter = new FileWriter(createTempFile);
		BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
		bufferedWriter.write("<search>" + result + "</search>" );
		bufferedWriter.flush();
		bufferedWriter.close();
		fileWriter.close();
		StringWriter w = new StringWriter();
		getTransformer("top10.xsl").transform( new StreamSource( createTempFile ), new StreamResult( w ) );
		w.flush();
		createTempFile.delete();
		String resultTransformed = w.toString();
		w.close();
		return resultTransformed;
		
	}
	
}
